import { computed } from 'vue'
import { defineStore } from 'pinia'
import { SUPPORTED_LANGUAGES, switchLanguage, locale } from '../../i18n'

export const useI18nStore = defineStore('i18n', () => {
  // 当前语言
  const currentLocale = computed(() => locale.value)
  
  // 支持的语言列表
  const languages = computed(() => SUPPORTED_LANGUAGES)
  
  // 切换语言
  const setLocale = (newLocale: string) => {
    switchLanguage(newLocale)
  }
  
  // 获取当前语言名称
  const getCurrentLanguageName = computed(() => {
    return SUPPORTED_LANGUAGES[currentLocale.value as keyof typeof SUPPORTED_LANGUAGES]?.name || '中文'
  })
  
  // 检测系统语言
  const getSystemLocale = (): string => {
    const navigatorLang = navigator.language.toLowerCase()
    for (const lang of Object.keys(SUPPORTED_LANGUAGES)) {
      if (navigatorLang.includes(lang)) {
        return lang
      }
    }
    return 'zh-cn'
  }
  
  // 初始化语言设置
  const initLocale = () => {
    const savedLocale = localStorage.getItem('app-language')
    if (!savedLocale) {
      const systemLocale = getSystemLocale()
      setLocale(systemLocale)
    }
  }
  
  return {
    currentLocale,
    languages,
    setLocale,
    getCurrentLanguageName,
    initLocale
  }
})